$(function () {
    var $rechargeBox = $('#recharge-box');
    var $rechargeNum = $rechargeBox.find('input');
    var $rechargeSub = $rechargeBox.find('button');
    var orderId;
    checkPayResult();
    $rechargeSub.on('click', function () {
        var rechargeNum = $rechargeNum.val();
        if (rechargeNum <= 0) {
            _alert('请输入正确的充值金额');
            return
        }
        orderId = new Date().getTime();
        setOrderId(orderId);
        ajax({
            url: 'app/pay/weixinPay',
            data: {
                amount: rechargeNum,
                orderId: orderId
            },
            success: function (d) {
                if (d.mwebUrl) {
                    window.location.href = d.mwebUrl;
                }
            }
        })
    })

    function checkPayResult() {
        if(!getOrderId())return;
        var timer = setInterval(function () {
            ajax({
                url: 'app/pay/weixinQuery',
                data: {
                    orderId: getOrderId()
                },
                success: function (d) {
                    _alert('支付成功');
                    if (timer) clearInterval(timer);
                    setOrderId('');
                    setTimeout(function(){
                        window.history.back();
                    },1000)
                }
            });
        }, 500);
    }
});